package server;

import java.io.*;

public class AppClassLoader extends ClassLoader {

    private String classpath ;


    public AppClassLoader(String classPath){
        classpath=classPath;
    }
    @Override
    protected Class<?> findClass(String className) throws ClassNotFoundException {
        try {
            InputStream in = null;
            ByteArrayOutputStream out = null;
            //将文件全路径转换为.class
            String path=classpath + File.separatorChar + className.replace('.', File.separatorChar)+".class";
            in=new FileInputStream(path);
            out=new ByteArrayOutputStream();
            byte[] buffer=new byte[2048];
            int len=0;
            while((len=in.read(buffer))!=-1){
                out.write(buffer,0,len);
            }
            byte [] classDate=out.toByteArray();
            if(classDate==null){}

            else{
                //defineClass方法将字节码转化为类
                return defineClass(className,classDate,0,classDate.length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return super.findClass(className);
    }

}
